// global highlighter object and key flag
var key;

// listen for key andclick events
var lines = document.querySelectorAll(".kix-lineview-text-block");
for(i = 0; i < lines.length; i++) {
    lines[i].onmouseup = attachHighlighter;
    lines[i].onkeydown = ctrlToggle;
    lines[i].onkeyup = ctrlToggle;
}

// event: on keydown
// description: if it's ctrl or cmd key, create highlighter
function ctrlToggle(e) {
    key = e.keyCode == 91 || e.keyCode == 93 && !key;
}

// event: on mousedown
// description: creates new highlighter object
function attachHighlighter(e) {
    // if ctrl or cmd is down, create a global highlighter
    if(key || e.ctrlKey) {
	this.highlighter = new Highlighter(this, e.detail);
    }
}

function Highlighter(startNode, numClicks) {
    // get the current selection
    if(window.getSelection){
	var selection = window.getSelection();
    } else if(document.selection){
	var selection = document.selection.createRange();
    }

    // get a range for the selection
    if (selection.getRangeAt)
	var range = selection.getRangeAt(0);
    else { 
	var range = document.createRange();
	range.setStart(selection.anchorNode,selection.anchorOffset);
	range.setEnd(selection.focusNode,selection.focusOffset);
    }

    // if clicked on same place once or twice,
    // highlight the line or paragraph respectively
    if(selection.anchorNode == selection.focusNode){
	console.log(numClicks);
	// if one click, highlight the line
	if(numClicks == 1) {
	    startNode.style.backgroundColor = "yellow";
	} 
	// if two clicks, highlight the paragraph
	else if(numClicks == 2) {
	    var parent = startNode.parentNode;
	    while(parent.classList[0] != "kix-paragraphrenderer") {
		parent = parent.parentNode;
	    }
	    parent.style.backgroundColor = "yellow";
	}
    }
    // otherwise we're going to be adding in a span
    var span = document.createElement('span');
    span.style.backgroundColor = "yellow";
    
    // see if the range will allow surroundContents nicely
    try {
	range.surroundContents(span);
    } catch(BAD_BOUNDARYPOINTS_ERR) {
	range.startContainer.insertData(range.startOffset, '<span style="background-color: yellow;">');
	range.endContainer.insertData(range.endtOffset, '</span>');
    }
}
